<template>
  <div v-if="visible" class="dialog-overlay" @click="handleClose">
    <div class="dialog" @click.stop>
      <div class="dialog-header">
        <h3>{{ title }}</h3>
        <button class="btn-close" @click="handleClose">×</button>
      </div>
      <div class="dialog-body">
        <div class="search-row">
          <input 
            v-model="searchKeyword" 
            class="form-input" 
            :placeholder="searchPlaceholder"
            @input="handleSearch"
            @keyup.enter="doSearch"
          />
          <button class="btn primary" @click="doSearch">
            搜索
          </button>
        </div>
        
        <div class="item-list">
          <div v-if="items.length === 0 && !searchKeyword.trim()" class="no-data">
            正在加载{{ type }}列表...
          </div>
          <div v-else-if="items.length === 0 && searchKeyword.trim()" class="no-data">
            未找到包含"{{ searchKeyword.trim() }}"的{{ type }}
          </div>
          <div v-else-if="items.length > 0" class="search-result-info">
            <span v-if="searchKeyword.trim()">找到 {{ items.length }} 个相关{{ type }}，点击选择：</span>
            <span v-else>{{ type }}列表（{{ items.length }} 个），点击选择：</span>
          </div>
          
          <div 
            v-for="item in items" 
            :key="item.id" 
            class="item-card"
            @click="selectItem(item)"
          >
            <div class="item-name">{{ getItemName(item) }}</div>
            <div class="item-code">{{ getItemCode(item) }}</div>
            <div class="item-desc">{{ getItemDesc(item) }}</div>
          </div>
        </div>
      </div>
    </div>
  </div>
  
  <!-- 数量选择对话框 -->
  <div v-if="showQuantityDialog" class="dialog-overlay" @click="showQuantityDialog = false">
    <div class="dialog quantity-dialog" @click.stop>
      <div class="dialog-header">
        <h3>设置医嘱参数 - {{ selectedItem?.name || getItemName(selectedItem) }}</h3>
        <button class="btn-close" @click="showQuantityDialog = false">×</button>
      </div>
      <div class="dialog-body">
        <div class="quantity-form">
          <div class="form-row" v-if="type === '药品'">
            <label>用法用量：</label>
            <input v-model="orderParams.dosage" type="number" min="1" class="form-input" placeholder="每次用量" />
            <span>{{ selectedItem?.unit || '片' }}/次</span>
          </div>
          
          <div class="form-row" v-if="type === '药品'">
            <label>用药频次：</label>
            <select v-model="orderParams.frequency" class="form-input">
              <option value="每日一次">每日一次</option>
              <option value="每日两次">每日两次</option>
              <option value="每日三次">每日三次</option>
              <option value="每日四次">每日四次</option>
              <option value="每8小时一次">每8小时一次</option>
              <option value="每12小时一次">每12小时一次</option>
              <option value="临时医嘱">临时医嘱</option>
            </select>
          </div>
          
          <div class="form-row" v-if="type === '药品'">
            <label>用药天数：</label>
            <input v-model="orderParams.days" type="number" min="1" max="30" class="form-input" placeholder="天数" />
            <span>天</span>
          </div>
          
          <div class="form-row">
            <label>{{ type === '药品' ? '总数量' : '数量' }}：</label>
            <input v-model="orderParams.quantity" type="number" min="1" class="form-input" placeholder="数量" />
            <span>{{ selectedItem?.unit || (type === '药品' ? '片' : '次') }}</span>
          </div>
          
          <div class="form-row" v-if="type !== '药品'">
            <label>单价：</label>
            <input v-model="orderParams.unitPrice" type="number" min="0" step="0.01" class="form-input" placeholder="单价" />
            <span>元</span>
          </div>
          
          <div class="form-row">
            <label>备注：</label>
            <input v-model="orderParams.remark" class="form-input" placeholder="医嘱备注（可选）" />
          </div>
          
          <div class="form-actions">
            <button class="btn secondary" @click="showQuantityDialog = false">取消</button>
            <button class="btn primary" @click="confirmAdd" :disabled="!isValidParams">确认添加</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'

const props = defineProps({
  visible: Boolean,
  type: String, // '药品', '诊疗项目', '医疗服务'
  title: String,
  searchPlaceholder: String,
  items: Array,
  onSearch: Function,
  onLoadDefault: Function
})

const emit = defineEmits(['close', 'add'])

const searchKeyword = ref('')
const searchTimer = ref(null)
const showQuantityDialog = ref(false)
const selectedItem = ref(null)

// 医嘱参数
const orderParams = ref({
  dosage: 1,
  frequency: '每日三次',
  days: 7,
  quantity: 1,
  unitPrice: 0,
  remark: ''
})

// 参数验证
const isValidParams = computed(() => {
  return orderParams.value.quantity > 0 && 
         (props.type === '药品' ? orderParams.value.dosage > 0 && orderParams.value.days > 0 : orderParams.value.unitPrice >= 0)
})

// 处理搜索
function handleSearch() {
  if (searchTimer.value) {
    clearTimeout(searchTimer.value)
  }
  
  if (!searchKeyword.value.trim()) {
    props.onLoadDefault?.()
    return
  }
  
  searchTimer.value = setTimeout(() => {
    doSearch()
  }, 500)
}

function doSearch() {
  props.onSearch?.(searchKeyword.value.trim())
}

// 获取项目名称
function getItemName(item) {
  if (!item) return ''
  // 根据不同类型使用不同的字段名
  return item.drugName || item.projectName || item.serviceName || item.itemName || item.name || ''
}

// 获取项目编码
function getItemCode(item) {
  if (!item) return ''
  const code = item.drugCode || item.projectCode || item.serviceCode || item.itemCode || item.code || ''
  const spec = item.specification || ''
  if (spec) {
    return `规格: ${spec}`
  }
  return code ? `编码: ${code}` : '编码: 无'
}

// 获取项目描述
function getItemDesc(item) {
  if (!item) return ''
  const unit = item.unit || item.unitOfMeasure || item.pricingUnit || ''
  const price = item.price || 0
  const desc = item.drugDescription || item.projectDescription || item.projectContent || item.serviceDescription || item.itemDescription || item.description || item.notes || ''
  
  let result = []
  if (unit) result.push(`单位: ${unit}`)
  if (price > 0) result.push(`价格: ${price}元`)
  if (desc && desc.length > 0) result.push(desc)
  
  return result.join(' | ') || '暂无描述'
}

// 选择项目
function selectItem(item) {
  selectedItem.value = item
  
  // 重置参数，使用正确的单位字段
  const unit = item.unit || item.unitOfMeasure || item.pricingUnit || ''
  
  orderParams.value = {
    dosage: 1,
    frequency: '每日三次',
    days: 7,
    quantity: props.type === '药品' ? 7 : 1, // 药品默认按天数计算
    unitPrice: item.price || 0,
    remark: ''
  }
  
  // 更新selectedItem的unit字段供显示使用
  if (unit) {
    selectedItem.value.unit = unit
  }
  
  showQuantityDialog.value = true
}

// 确认添加
function confirmAdd() {
  const orderData = {
    item: selectedItem.value,
    params: { ...orderParams.value }
  }
  
  emit('add', orderData)
  showQuantityDialog.value = false
  handleClose()
}

// 关闭对话框
function handleClose() {
  emit('close')
  searchKeyword.value = ''
  selectedItem.value = null
  showQuantityDialog.value = false
}

// 监听visible变化，自动加载默认数据
watch(() => props.visible, (newVal) => {
  if (newVal) {
    searchKeyword.value = ''
    props.onLoadDefault?.()
  }
})
</script>

<style scoped>
/* 对话框样式 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.dialog {
  background: white;
  border-radius: 8px;
  width: 600px;
  max-width: 90vw;
  max-height: 80vh;
  overflow: hidden;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
}

.quantity-dialog {
  width: 500px;
}

.dialog-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  background: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
}

.dialog-header h3 {
  margin: 0;
  color: #34495e;
  font-size: 16px;
}

.btn-close {
  background: none;
  border: none;
  font-size: 24px;
  color: #999;
  cursor: pointer;
  padding: 0;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: background 0.2s;
}

.btn-close:hover {
  background: #e9ecef;
}

.dialog-body {
  padding: 20px;
  max-height: 60vh;
  overflow-y: auto;
}

.search-row {
  display: flex;
  gap: 10px;
  margin-bottom: 16px;
}

.search-row .form-input {
  flex: 1;
}

.item-list {
  max-height: 400px;
  overflow-y: auto;
}

.item-card {
  padding: 12px;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  margin-bottom: 8px;
  cursor: pointer;
  transition: all 0.2s;
}

.item-card:hover {
  background: #e3f2fd;
  border-color: #2196f3;
}

.item-name {
  font-size: 14px;
  color: #34495e;
  font-weight: 500;
  margin-bottom: 4px;
}

.item-code {
  font-size: 12px;
  color: #999;
}

.item-desc {
  font-size: 12px;
  color: #666;
  margin-top: 2px;
}

.item-card:hover .item-name {
  color: #2196f3;
}

.item-card:hover .item-code {
  color: #2196f3;
}

.no-data {
  color: #999;
  font-style: italic;
  padding: 16px;
  text-align: center;
  background: #f8f9fa;
  border-radius: 6px;
}

.search-result-info {
  padding: 8px 12px;
  background: #e8f5e8;
  color: #2e7d32;
  border-radius: 4px;
  margin-bottom: 8px;
  font-size: 13px;
  border: 1px solid #c8e6c9;
}

/* 数量设置表单样式 */
.quantity-form {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.form-row {
  display: flex;
  align-items: center;
  gap: 8px;
}

.form-row label {
  min-width: 80px;
  font-weight: 500;
  color: #34495e;
}

.form-row .form-input {
  flex: 1;
  height: 36px;
  border-radius: 6px;
  border: 1px solid #dcdfe6;
  padding: 0 10px;
  font-size: 14px;
  box-sizing: border-box;
}

.form-row .form-input:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px #eaf4ff;
}

.form-row span {
  color: #666;
  font-size: 14px;
  min-width: 40px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
  padding-top: 16px;
  border-top: 1px solid #e9ecef;
}

.btn {
  padding: 8px 16px;
  border-radius: 6px;
  border: none;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.btn.primary {
  background: #409eff;
  color: #fff;
}

.btn.primary:hover {
  background: #3076c9;
}

.btn.primary:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.btn.secondary {
  background: #f5f6fa;
  color: #34495e;
  border: 1px solid #dcdfe6;
}

.btn.secondary:hover {
  background: #e8e9eb;
}
</style>
